<template>

    <el-button type="success" plain @click="OpenAddUser">
        新增
    </el-button>

    <div style="border-style:groove;border-width: 2px;margin-bottom: 20px;height: 550px;">
        <el-table :data="tableData" border style="width: 100%;height: 500px;">
            <el-table-column type="index" label="编号" />
            <el-table-column prop="userName" label="用户名" />
            <el-table-column prop="sex" label="性别">
                <template v-slot="scoped">
                    {{ scoped.row.sex == true ? "男" : "女" }}
                </template>
            </el-table-column>
            <el-table-column prop="roleName" label="角色" />
            <el-table-column prop="shen" label="所在省份" />
            <el-table-column prop="shi" label="所在市" />
            <el-table-column prop="xian" label="所在县" />
            <el-table-column prop="desc" label="地址详情">
                <template v-slot="scoped">
                    <el-tooltip :content="scoped.row.desc" placement="top">
                        <p v-show="scoped.row.desc.length > 5">{{ scoped.row.desc.substring(0, 5) + "....." }}</p>

                    </el-tooltip>
                    <p v-show="scoped.row.desc.length <= 5">{{ scoped.row.desc }}</p>
                </template>
            </el-table-column>

            <el-table-column prop="createUserName" label="创建人" />
            <el-table-column prop="createTime" label="创建日期" width="100px">
                <template v-slot="scoped">
                    {{ moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
                </template>
            </el-table-column>
            <el-table-column prop="updateUserName" label="修改人">
                <template v-slot="scoped">
                    {{ scoped.row.updateUserName == null ? "" : scoped.row.updateUserName }}
                </template>
            </el-table-column>
            <el-table-column prop="upDataTime" label="修改日期" width="100px">
                <template v-slot="scoped">
                    {{ scoped.row.upDataTime == "0001-01-01T00:00:00" ? "" :
                        moment(scoped.row.upDataTime).format("YYYY-MM-DD HH:mm:ss ") }}
                </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="200px">
                <template v-slot="scoped">
                    <el-button type="danger" plain @click="Del(scoped.row.id)">删除</el-button>
                    <el-button type="primary" plain @click="openUpdata(scoped.row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="demo-pagination-block">


            <el-pagination v-model:current-page="PageData.PageIndex" v-model:page-size="PageData.PageSize"
                :page-sizes="[15, 20, 25, 30]" :background="true
                    " layout="total, sizes, prev, pager, next, jumper" :total="PageData.count" prev-text="上一页"
                next-text="下一页" />
        </div>
    </div>




    <!-- 新增 -->
    <el-dialog v-model="dialogFormVisible" title="新增" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="ruleForm.userName" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="ruleForm.sex">
                    <el-radio :value="true">男</el-radio>
                    <el-radio :value="false">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <!--             <el-form-item label="所在地区" prop="">
                <el-select v-model="ruleForm.shen" placeholder="Activity zone" style="width: 120px;">
                    <el-option label="请选择省份" value="0" />
                    <el-option v-for="item in ShengData" :label="item.addressName" :value="item.id" />
                </el-select>
                <el-select v-model="ruleForm.shi" placeholder="Activity zone" style="width: 120px;">
                    <el-option label="请选择市" value="0" />
                    <el-option v-for="item in SHiData" :label="item.addressName" :value="item.id" />
                </el-select>
                <el-select v-model="ruleForm.xian" placeholder="Activity zone" style="width: 120px;">
                    <el-option label="请选择县" value="0" />
                    <el-option v-for="item in XianData" :label="item.addressName" :value="item.id" />
                </el-select>

            </el-form-item> -->

            <el-form-item label="所在地址">
                <el-select placeholder="请选择省份" @change="handleProvinceChange" v-model="ruleForm.shen"
                    style="width: 110px;margin-right: 20px;">
                    <el-option v-for="a in provinceList" :key="a.value" :label="a.label" :value="a.label" />
                </el-select>
                <el-select placeholder="请选择市" @change="handleCityChange" v-model="ruleForm.shi" style="width: 110px;">
                    <el-option v-for="a in cityList" :key="a.value" :label="a.label" :value="a.label" />
                </el-select>
                <el-select placeholder="请选择县" v-model="ruleForm.xian" style="width: 110px;margin-left: 20px;">
                    <el-option v-for="a in districtList" :key="a.value" :label="a.label" :value="a.label" />
                </el-select>
            </el-form-item>


            <el-form-item label="所在区域" prop="desc">
                <el-input v-model="ruleForm.desc" type="textarea" />
            </el-form-item>

            <el-form-item label="部门" prop="">

                <el-select v-model="ruleForm.deptId" placeholder="" style="width: 120px;">
                    <el-option v-for="item in DeptData" :label="item.label" :value="item.id" />
                </el-select>

            </el-form-item>



            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog v-model="Update" title="修改" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="ruleForm.userName" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="ruleForm.sex">
                    <el-radio :value="true">男</el-radio>
                    <el-radio :value="false">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <!--   <el-form-item label="所在地区" prop="">
                <el-select v-model="ruleForm.shen" placeholder="Activity zone" style="width: 120px;">
                    <el-option label="请选择省份" value="0" />
                    <el-option v-for="item in ShengData" :label="item.addressName" :value="item.id" />
                </el-select>
                <el-select v-model="ruleForm.shi" placeholder="Activity zone" style="width: 120px;">
                    <el-option label="请选择市" value="0" />
                    <el-option v-for="item in SHiData" :label="item.addressName" :value="item.id" />
                </el-select>
                <el-select v-model="ruleForm.xian" placeholder="Activity zone" style="width: 120px;">
                    <el-option label="请选择县" value="0" />
                    <el-option v-for="item in XianData" :label="item.addressName" :value="item.id" />
                </el-select>

            </el-form-item> -->
            <el-form-item label="所在地址">

                <el-select placeholder="请选择省份" @change="handleProvinceChange" v-model="ruleForm.shen"
                    style="width: 110px;margin-right: 20px;">
                    <el-option v-for="a in provinceList" :key="a.value" :label="a.label" :value="a.label" />
                </el-select>
                <el-select placeholder="请选择市" @change="handleCityChange" v-model="ruleForm.shi" style="width: 110px;">
                    <el-option v-for="a in cityList" :key="a.value" :label="a.label" :value="a.label" />
                </el-select>
                <el-select placeholder="请选择县" v-model="ruleForm.xian" style="width: 110px;margin-left: 20px;">
                    <el-option v-for="a in districtList" :key="a.value" :label="a.label" :value="a.label" />
                </el-select>
            </el-form-item>


            <el-form-item label="所在区域" prop="desc">
                <el-input v-model="ruleForm.desc" type="textarea" />
            </el-form-item>



            <el-form-item>
                <el-button type="primary" @click="UpdatesubmitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


</template>

<script lang="ts" setup>

import { onMounted, ref, watch, reactive } from 'vue';
import moment from 'moment';
import axios from 'axios';
import { readB } from '@/http/axiosHelper'

const dialogFormVisible = ref(false)
const Update = ref(false)
const formLabelWidth = '140px'

const tableData = ref([]);
const PageData = ref({
    PageIndex: 1,
    PageSize: 15,
    count: 0,
})

watch(() => { PageData.value.PageIndex, PageData.value.PageSize }, () => {
    ShowUser();
}, { deep: true })


const ShowUser = () => {
    readB.get("/api/Management/GetUserInfo", {
        params: {
            PageIndex: PageData.value.PageIndex,
            PageSize: PageData.value.PageSize
        }
    })
        .then(res => {
            if (res.data.code == 200) {



                tableData.value = res.data.pageData;
                PageData.value.count = res.data.count;

            }
        })
}


const openUpdata = async (row: any) => {
    Object.assign(ruleForm, row);
    Update.value = true;
}

const DeptData = ref([
    {
        id: 1,
        label: 'IT信息部',
    },
    {
        id: 2,
        label: '人力资源部',
    },
    {
        id: 3,
        label: '财务部',
    },

    {
        id: 4,
        label: '销售部',
    },
    {
        id: 5,
        label: '行政部',
    }
])

//-----添加

import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { dataType } from 'element-plus/es/components/table-v2/src/common.mjs';






const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "id": 0,
    "userName": "",
    "sex": true,
    "shen": "",
    "shi": "",
    "xian": "",
    "desc": "",
    "deptId": 1
})



const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    userName: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },

    ],

    desc: [
        { required: true, message: '详情地址不能为空', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm);

            readB.post("/api/Management/AddUser", ruleForm)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        dialogFormVisible.value = false
                        ShowUser();
                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const UpdatesubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm);

            readB.post("/api/Management/UPdateUser", ruleForm)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        Update.value = false
                        ShowUser();

                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const OpenAddUser = () => {
    dialogFormVisible.value = true
    ruleForm.desc = ""
    ruleForm.userName = ""
    ruleForm.shen = ""
    ruleForm.shi = ""
    ruleForm.xian = ""
    ruleForm.desc = ""
    /* GetAddressSheng(); */
}
/* 
const ShengData = ref([{
    addressName: "",
    id: ""
}])
const GetAddressSheng = () => {
    readB.get("/api/Management/GetAddress", {
        params: {
            Id: 0
        }
    })
        .then(res => {
            ShengData.value = res.data.data
        })
}

const SHiData = ref([{
    addressName: "",
    id: ""
}])
const GetAddressShi = () => {
    readB.get("/api/Management/GetAddress", {
        params: {
            Id: ruleForm.shen
        }
    })
        .then(res => {
            SHiData.value = res.data.data
        })
}

const XianData = ref([{
    addressName: "",
    id: ""
}])
const GetAddressXian = () => {
    readB.get("/api/Management/GetAddress", {
        params: {
            Id: ruleForm.shi
        }
    })
        .then(res => {
            XianData.value = res.data.data
        })
} */

onMounted(() => {
    ShowUser();

})

/* watch(() => { PageData.value.PageIndex, PageData.value.PageSize }, () => {
    ShowUser();
}, {
    deep: true
})

watch(() => { ruleForm.shen }, () => {
    ruleForm.shi = "0"
    GetAddressShi();
}, {
    deep: true
})

watch(() => { ruleForm.shi }, () => {
    ruleForm.xian = "0"
    GetAddressXian();
}, {
    deep: true
}) */


import { ElMessageBox } from 'element-plus'
const Del = (id: any) => {
    ElMessageBox.confirm(
        '确认删除么?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            readB.post("/api/Management/DelUser", null, {
                params: {
                    Id: id
                }
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg);
                        ShowUser();
                    }
                    else {
                        ElMessage.error(res.data.msg);
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}


/* const form = reactive({
    market: "",//shi
    county: "",//xian
    province: ""//shen
}) */
//省份改变时，加载对应城市
const handleProvinceChange = (provinceCode: string) => {
    ruleForm.shi = ''
    ruleForm.xian = ''

    const province = regionData.find(item => item.label === provinceCode)
    if (province && province.children) {
        cityList.value = province.children
    }
    else {
        cityList.value = []
    }
}

//城市改变时，加载对应的区县
const handleCityChange = (cityCode: string) => {
    ruleForm.xian = ''
    const province = regionData.find(item => item.label === ruleForm.shen)
    if (province) {
        const city = province.children?.find(item => item.label === cityCode)
        if (city?.children) {
            districtList.value = city.children
        }
        else {
            districtList.value = []
            console.warn('当前城市无区县数据')
        }
    }
}
//监听provinceId变化，初始化区县列表
watch(() => ruleForm.shen, (newVal) => {
    if (newVal) {
        handleProvinceChange(newVal)
    }
})
//监听cityId变化，初始化区县列表
watch(() => ruleForm.shi, (newVal) => {
    if (newVal) {
        handleCityChange(newVal)
    }
})

//省市县全国
import { regionData, codeToText } from 'element-china-area-data';
//省份列表
const provinceList = regionData
//城市列表
const cityList = ref<any[]>([])
//区县列表
const districtList = ref<any[]>([])

</script>